﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Class { get; set; }

    public Student(int id, string name, int age, string className)
    {
        Id = id;
        Name = name;
        Age = age;
        Class = className;
    }

    public override string ToString()
    {
        return $"学号: {Id}, 姓名: {Name}, 年龄: {Age}, 班级: {Class}";
    }
}

public class StudentManager
{
    private List<Student> _students = new List<Student>();

    public void AddStudent(Student student)
    {
        if (_students.Exists(s => s.Id == student.Id))
        {
            Console.WriteLine($"错误：学号为{student.Id}的学生已存在！");
            return;
        }
        _students.Add(student);
        Console.WriteLine($"学生{student.Name}添加成功！");
    }

    public List<Student> GetStudents()
    {
        return _students;
    }

    public void SetStudents(List<Student> students)
    {
        _students = students;
    }

    public void TraverseAllStudents()
    {
        if (_students.Count == 0)
        {
            Console.WriteLine("当前没有学生信息！");
            return;
        }

        Console.WriteLine("\n所有学生信息如下：");
        foreach (var student in _students)
        {
            Console.WriteLine(student);
        }
        Console.WriteLine();
    }
}

public class StudentJsonHandler
{
    public void SerializeAndSave(List<Student> students, string filePath)
    {
        var options = new JsonSerializerOptions { WriteIndented = true };
        string json = JsonSerializer.Serialize(students, options);
        File.WriteAllText(filePath, json);
        Console.WriteLine($"学生集合已序列化并保存到 {filePath}");
    }

    public List<Student> DeserializeAndLoad(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Console.WriteLine($"文件 {filePath} 不存在！");
            return new List<Student>();
        }

        string json = File.ReadAllText(filePath);
        return JsonSerializer.Deserialize<List<Student>>(json) ?? new List<Student>();
    }
}

public class StudentJsonTest
{
    public static void Main(string[] args)
    {
        string filePath = "students.json";
        StudentManager manager = new StudentManager();
        StudentJsonHandler handler = new StudentJsonHandler();

        manager.AddStudent(new Student(1001, "张三", 18, "计算机一班"));
        manager.AddStudent(new Student(1002, "李四", 19, "计算机二班"));
        manager.AddStudent(new Student(1003, "王五", 18, "计算机一班"));

        Console.WriteLine("===== 序列化并保存 =====");
        handler.SerializeAndSave(manager.GetStudents(), filePath);

        Console.WriteLine("===== 反序列化并读取 =====");
        List<Student> loadedStudents = handler.DeserializeAndLoad(filePath);
        manager.SetStudents(loadedStudents);
        manager.TraverseAllStudents();

        Console.ReadLine();
    }
}